package xin.shaozeming.base.common.servlet.interceptor;

import io.swagger.annotations.ApiParam;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xin.shaozeming.base.common.aop.annotation.ParamsDecrypted;
import xin.shaozeming.base.common.utils.DateUtils;
import xin.shaozeming.base.common.utils.DecryptUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: 邵泽铭
 * @date: 2018/8/29
 * @description:
 **/
public class DecryptInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        decryptParams(request, handler);
        return super.preHandle(request, response, handler);
    }


    private void decryptParams(HttpServletRequest request, Object handler) {


        if (handler instanceof HandlerMethod&&((HandlerMethod) handler).getMethod().getAnnotation(ParamsDecrypted.class) != null) {

            /*取出所有的参数*/
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (parameterMap.size() == 0) {
                return;
            }

            for (Map.Entry<String, String[]> kv : parameterMap.entrySet()) {

                /*解密数据*/
                String value = DecryptUtil.decryptParam(request.getHeader("key"), kv.getValue()[0]);
             /*   *//*正则匹配多重属性*//*
                Pattern pattern = Pattern.compile("(?<=\\[)\\w+?(?=\\])");
                Matcher matcher = pattern.matcher(kv.getKey());
                List<String> attrList = new ArrayList<>();
                while (matcher.find()) {
                    attrList.add(matcher.group());
                }*/

                parameterMap.put(kv.getKey(), new String[]{value});


            }


        }

    }


}

